<template>
    <section class="card_con">
        <div class="card_title">客易达应用服务</div>
        <!-- <a href="/scrm-guide" target="_blank" class="guide-box">配置引导</a> -->
        <div class="card_list">
            <el-card v-for="item in card.list" :key="item.id" class="box_card">
                <!-- <div :style="`background-image:url(${item.icon})`" class="card_item_image"></div> -->
                <img :src="item.application?.icon" alt="" class="card_item_image" />
                <div class="card_bottom">
                    <span class="item_card_tit">{{ item.application && item.application.name }}</span>
                    <el-popover v-if="item.application.desc.length > 30" placement="top" :width="300" trigger="hover">
                        <template #reference>
                            <div class="item_card_desc">
                                {{ item.application && item.application.desc }}
                            </div>
                        </template>
                        <template #default>
                            <div class="item_card_desc">
                                {{ item.application && item.application.desc }}
                            </div>
                        </template>
                    </el-popover>
                    <div v-else class="item_card_desc">
                        {{ item.application && item.application.desc }}
                    </div>
                    <div v-if="[12, 13].includes(item.zw_app_id)" class="btn_bottom">
                        <!-- 自营店铺和客易达会员通，展示查看店铺 -->
                        <el-button type="primary" @click="goShop(+item.third_type)">查看店铺</el-button>
                    </div>
                    <div v-else class="btn_bottom">
                        <el-button v-if="item.zw_app_id != 3" plain @click="configureBoot(item)"> 配置引导 </el-button>
                        <!-- 外链暂时隐藏 -->
                        <!-- <el-button plain @click="configureBoot(item)">配置引导</el-button> -->
                        <el-button
                            v-if="item.is_grant === 2"
                            v-auth="'SETTING_INFORMATION'"
                            type="primary"
                            @click="ConfigInfo(item)">
                            配置信息
                        </el-button>
                        <el-button
                            v-else
                            v-auth="'BEGIN_SETTING'"
                            type="info"
                            class="add_btn type_info"
                            @click="goAuthorizationConfig">
                            开始配置
                        </el-button>
                    </div>
                </div>
            </el-card>
            <el-empty v-if="!card.list.length" image="/static/noData.png" description="暂无数据" />
        </div>
        <div class="card_title">第三方应用集成</div>
        <!-- <a href="/scrm-guide" target="_blank" class="guide-box">配置引导</a> -->
        <div class="card_list">
            <el-card v-for="item in card.thirdList" v-show="item.is_add == 1" :key="item.id" class="box_card">
                <!-- <div :style="`background-image:url(${item.icon})`" class="card_item_image"></div> -->
                <img :src="item.icon ? item.icon : item.icon" alt="" class="card_item_image" />
                <div class="card_bottom">
                    <span class="item_card_tit">{{ item.name && item.name }}</span>
                    <el-popover v-if="item.desc.length > 30" placement="top" :width="300" trigger="hover">
                        <template #reference>
                            <div class="item_card_desc">
                                {{ item.desc && item.desc }}
                            </div>
                        </template>
                        <template #default>
                            <div class="item_card_desc">
                                {{ item.desc && item.desc }}
                            </div>
                        </template>
                    </el-popover>
                    <div v-else class="item_card_desc">
                        {{ item.desc && item.desc }}
                    </div>
                    <div class="btn_bottom">
                        <!-- <el-button plain @click="configureBoot(item)">配置引导</el-button> -->
                        <el-button v-if="item.third_type == 2" type="primary" @click="ConfigInfo(item)">
                            <span>配置信息</span>
                        </el-button>
                        <el-button v-else type="primary" @click="goShop(+item.third_type)"> 查看店铺 </el-button>
                    </div>
                </div>
            </el-card>
            <el-empty v-if="!card.thirdList.length" image="/static/noData.png" description="暂无数据" />
        </div>

        <!-- 内容可编辑 -->
        <Dialog :app-dialog="appDialog">
            <el-form ref="formRef" class="app_form" :model="formData" label-width="170px" label-position="right">
                <!-- 企业通讯录配置 -->
                <h4>应用配置</h4>
                <el-form-item label="可信域名:">
                    <div v-for="item in formData.trusted_domain" :key="item">
                        <span>{{ item }}</span>
                        <CopyText :copy-data="item" />
                    </div>
                </el-form-item>
                <el-form-item label="主页地址:">
                    <span>{{ formData.application_url }}</span>
                    <CopyText :copy-data="formData.application_url" />
                </el-form-item>

                <!-- 侧边栏配置 -->
                <h4>侧边栏配置</h4>
                <el-form-item label="内容引擎页面地址:">
                    <span>{{ formData.talk_url_config.content_url }}</span>
                    <CopyText
                        v-if="IsNotEmpty(formData.talk_url_config.content_url)"
                        :copy-data="formData.talk_url_config.content_url" />
                </el-form-item>
                <el-form-item label="客户详情页地址:">
                    <span>{{ formData.talk_url_config.custDetail_url }}</span>
                    <CopyText :copy-data="formData.talk_url_config.custDetail_url" />
                </el-form-item>
                <el-form-item label="高级素材库:">
                    <span> {{ formData.talk_url_config.advanced_material_url }}</span>
                    <CopyText :copy-data="formData.talk_url_config.advanced_material_url" />
                </el-form-item>
                <el-form-item label="电商素材:">
                    <span> {{ formData.talk_url_config.retail_url }}</span>
                    <CopyText :copy-data="formData.talk_url_config.retail_url" />
                </el-form-item>
                <el-form-item label="营销活动:">
                    <span> {{ formData.talk_url_config.market_code }}</span>
                    <CopyText :copy-data="formData.talk_url_config.market_code" />
                </el-form-item>
                <el-form-item label="员工红包:">
                    <span> {{ formData.talk_url_config.employee_red_packet }}</span>
                    <CopyText :copy-data="formData.talk_url_config.employee_red_packet" />
                </el-form-item>
                <el-form-item label="渠道素材:">
                    <span> {{ formData.talk_url_config.channel_material }}</span>
                    <CopyText :copy-data="formData.talk_url_config.channel_material" />
                </el-form-item>
            </el-form>
        </Dialog>
        <el-dialog
            v-model="onlineRetailersDialog"
            custom-class="enterprise_modal"
            width="600px"
            title="客易达电商应用配置"
            draggable
            :before-close="btnCancel">
            <div class="account_content">
                <img src="/static/appmarket/logo.png" style="margin-right: 16px" />
                <div>
                    <p>应用已添加，请妥善保管配置信息：</p>
                    <p style="margin: 14px 0">
                        App Key： &nbsp;&nbsp;&nbsp;{{ formData.shop_info.key }}
                        <CopyText :copy-data="formData.shop_info.key" />
                    </p>
                    <p>
                        App Secret：{{ formData.shop_info.secret }} <CopyText :copy-data="formData.shop_info.secret" />
                    </p>
                </div>
            </div>
            <template #footer>
                <el-button type="primary" @click="router.push('/ecommerce/storeManage/list')"> 店铺管理 </el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="qrcodeVisible" custom-class="enterprise_modal" width="300px" @close="handleClose">
            <template #title> 请扫描二维码 </template>
            <img v-if="qrcode" :src="qrcode" />
            <span v-else>获取二维码中...</span>
        </el-dialog>
        <!-- 抖音开发配置 -->
        <el-dialog
            v-model="trill.isShow"
            custom-class="enterprise_modal trillDialog"
            width="600px"
            :title="trill.title"
            draggable
            :before-close="btnCancel2">
            <el-form ref="formRef" :rules="rules" :model="trillForm" class="trillForm">
                <el-form-item label-width="">
                    <p class="title">授权的抖音企业号将同步以下信息：</p>
                </el-form-item>
                <el-form-item label-width="130px" label="实时同步">
                    <div class="sync_btn">
                        <el-switch v-model="trillForm.is_async" active-value="1" inactive-value="2" />
                        <span class="btn_text">开启后，抖音粉丝将实时同步至客户公海</span>
                    </div>
                </el-form-item>
                <el-form-item v-if="trillForm.is_async == '1'" label-width="130px" prop="cust_seas_id" label="至公海 ">
                    <el-select v-model="trillForm.cust_seas_id" placeholder="请选择客户公海">
                        <el-option v-for="item in seaids" :key="item.id" :value="item.id" :label="item.name">
                            {{ item.name }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="trillForm.is_async == '1'" label-width="130px" label="同步粉丝" prop="is_sync_fans">
                    <div class="sync_btn">
                        <el-switch v-model="trillForm.is_sync_fans" active-value="1" inactive-value="2" />
                        <span class="btn_text">开启后，抖音粉丝将实时同步至客户公海</span>
                    </div>
                </el-form-item>
                <el-form-item
                    v-if="trillForm.is_async == '1'"
                    label-width="130px"
                    label="同步意向用户"
                    prop="is_sync_potential_clients">
                    <div class="sync_btn">
                        <el-switch v-model="trillForm.is_sync_potential_clients" active-value="1" inactive-value="2" />
                        <span class="btn_text">开启后，抖音意向用户将实时同步至客户公海</span>
                    </div>
                </el-form-item>
                <el-form-item> </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="goCustomer"> 查看客户 </el-button>
                <el-button type="primary" @click="trillSave(formRef)"> 保存配置 </el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="qrcodeVisible" custom-class="enterprise_modal" width="300px" @close="handleClose">
            <template #title> 请扫描二维码 </template>
            <img v-if="qrcode" :src="qrcode" />
            <span v-else>获取二维码中...</span>
        </el-dialog>
    </section>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';
import { store } from '@/store';
import {
    getMyAppList,
    getThirdAppList,
    getAuthStatus,
    getCustomizedtAppQrcode,
    thirdConfig,
    lookThird,
    getLink
} from '@/api/appmarket';
import { getChannelConfigInfo, setContactSecret, setCustomerSecret, commonLink } from '@/api/channel/authconfig';
import { customerList } from '@/api/customer/clubManage/commonSea';
import Dialog from '@/components/Dialog.vue';
import CopyText from '@/components/CopyText.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { IsNotEmpty } from '@/utils/utils';

import { useRoute } from 'vue-router';
import router from '@/router';
import { groupCustomer } from '@/api/channel/operation';
const route = useRoute();
const formRef = ref();
const onlineRetailersDialog = ref(false);
const seaids = ref([]); //客户公海列表

const trill = reactive({
    title: '',
    isShow: false
});
const card = reactive({
    list: [
        {
            id: 1,
            is_grant: 1,
            icon: '',
            name: '',
            desc: '',
            application: {
                name: '',
                desc: ''
            }
        }
    ],
    channelList: [
        {
            id: 1,
            is_grant: 1,
            icon: '',
            name: '',
            desc: '',
            application: {
                name: '',
                desc: ''
            }
        }
    ],
    thirdList: [
        {
            id: 1,
            is_grant: 1,
            icon: '',
            name: '',
            desc: '',
            is_add: 1,
            type: 1,
            third_type: 1,
            source_id: []
        }
    ]
});
const rules = reactive({
    cust_seas_id: [{ required: true, message: '请选择客户公海', trigger: 'blur' }],
    is_sync_fans: [{ required: true, message: '请开启同步粉丝', trigger: 'blur' }],
    is_sync_potential_clients: [{ required: true, message: '请开启同步意向用户', trigger: 'blur' }]
});
const trillForm = reactive({
    app_id: 1, //应用id
    app_type: 1, //应用类型 1-抖音粉丝
    is_async: '1', //是否自动同步
    cust_seas_id: '', //同步公海id
    is_sync_fans: '1', //是否开启同步粉丝 1-开启 2-关闭
    is_sync_potential_clients: '1' //是否开启同步意向客户 1-开启 2-关闭
});
onMounted(() => {
    // 获取我的应用列表
    renderMyAppList();
});

// 获取我的应用列表
const renderMyAppList = async () => {
    const data = await getMyAppList();
    const third = await getThirdAppList();
    const { customized_app_auth } = await getAuthStatus();
    // 代开发: 客易达
    let is_grant = 1;
    if (customized_app_auth) {
        is_grant = 2;
    } else {
        is_grant = 1;
    }
    card.list = data;
    card.thirdList = third;
};
const goCustomer = (data: any) => {
    const str = trillForm.source_id.join(',');
    router.push(`/customer/manage/list?str=${str}`);
};

//保存去授权
const submitHandel = () => {
    appDialog.visible = false;
    window.open('/scrm-guide', '_blank');
};

const customerSercetDisabled = ref(true);
const contactSercetDisabled = ref(true);
const appDialog = reactive({
    visible: false,
    title: '客易达SCRM应用详情',
    width: '1000px',
    submitText: '查看指引',
    submit: submitHandel
});
const formData = reactive({
    contact: {
        secret: '',
        url: ''
    },
    token: '',
    aeskey: '',
    customer: {
        secret: '',
        url: ''
    },
    trusted_domain: [],
    application_url: '',
    talk_url_config: {
        content_url: ''
    },
    shop_info: {
        key: '',
        secret: ''
    }
});
// 查看店铺
const goShop = (num: any) => {
    router.push('/ecommerce/storeManage/list');
};

const ConfigInfo = async (val: any) => {
    if (val.zw_app_id == 2) {
        appDialog.visible = true;
    } else if (val.third_type == 2) {
        trillForm.app_id = val.id;
        trill.isShow = true;
        trill.title = `【${val.name}】配置信息`;
        lookThird({ app_id: val.id, app_type: 1 }).then((res: any) => {
            res.cust_seas_id = +res.cust_seas_id;
            Object.assign(trillForm, res);
        });
    } else {
        onlineRetailersDialog.value = true;
    }
    const res = await getChannelConfigInfo();
    formData.shop_info = res.shop_info;
    for (const key in res) {
        formData[key] = res[key];
    }
};
const configureBoot = async (val: any) => {
    if (val.zw_app_id == 2) {
        window.open('/scrm-guide', '_blank');
    } else {
        const res = await commonLink({ code: 'kyd_guide' });
        window.open(res.url, '_blank');
    }
};
const btnCancel = () => {
    onlineRetailersDialog.value = false;
};
const btnCancel2 = () => {
    if (!formRef.value) return;
    formRef.value.resetFields();
    trill.isShow = false;
};
const trillSave = async formEl => {
    if (!formRef.value) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            thirdConfig(trillForm).then((res: any) => {
                btnCancel2();
                ElMessage.success('配置成功');
            });
        }
    });
};
const cancelSecret = {
    contact: '',
    customer: ''
};
// 取消sercet
const handleContactSercetEdit = () => {
    cancelSecret.contact = formData.contact.secret;
    contactSercetDisabled.value = false;
};
const handleContactSercetSave = async () => {
    await setContactSecret({ secret: formData.contact.secret });
    contactSercetDisabled.value = true;
};
const handleCustomerSercetEdit = () => {
    cancelSecret.customer = formData.customer.secret;
    customerSercetDisabled.value = false;
};
const handleCustomerSercetSave = async () => {
    await setCustomerSecret({ secret: formData.customer.secret });
    customerSercetDisabled.value = true;
};
// 取消修改sercet
const handleSercetCancel = (key: string) => {
    formData[key].secret = cancelSecret[key];
    key === 'contact' ? (contactSercetDisabled.value = true) : (customerSercetDisabled.value = true);
};
const goAuthorizationConfig = async () => {
    const { suite_auth } = await getAuthStatus();
    if (!suite_auth) {
        ElMessageBox.confirm('您还没有授权客易达SCRM管理您的企业微信<br/>请授权后再添加应用！', {
            dangerouslyUseHTMLString: true,
            center: true
        }).then(() => {
            doAuthorization();
        });
    } else {
        // 需要做个渠道是否添加成功，如果成功再跳转至授权配置页面
        router.push('/scrm-guide');
    }
};
// 去授权
const doAuthorization = async () => {
    const currentCorp = store.getters['user/getCurrentCorp'] || '';
    const params = {
        new_corp_id: currentCorp,
        callback_front_url: location.href
    };
    const resUrl = await getLink(params);
    createLinkEle(resUrl.link);
    // pollGetStatus()
};
const createLinkEle = (linkHref: string) => {
    let a: HTMLAnchorElement | null = document.createElement('a');
    a.href = linkHref;
    a.target = '_blank';
    a.click();
    a = null;
};
// 查看二维码
const qrcode = ref('');
const qrcodeVisible = ref(false);
const timeId = ref();
const handleGetCustomizedtAppQrcode = async () => {
    qrcodeVisible.value = true;
    const data = await getCustomizedtAppQrcode();
    qrcode.value = data.qrcode;
    pollGetStatus();
};
// 轮询查状态
let pollGetStatus: any = () => {
    timeId.value = setInterval(async () => {
        const { suite_auth, customized_app_auth } = await getAuthStatus();
        if (customized_app_auth) {
            clearInterval(timeId.value);
            renderMyAppList();
            qrcodeVisible.value = false;
        }
    }, 1000);
};

// 关闭弹框时销毁
const handleClose = () => {
    clearInterval(timeId.value);
};
//获取公海列表
const getSeaList = () => {
    customerList({ page: 1, page_size: 9999 }).then((res: any) => {
        seaids.value = res;
    });
};
getSeaList();
onBeforeUnmount(() => {
    clearInterval(timeId.value);
    pollGetStatus = null;
});
</script>
<style scoped lang="scss">
@import '../index';

.card_title {
    display: inline-block;
}

.guide-box {
    margin-left: 20px;
    color: #ff6b00;
}

.app_form {
    padding-bottom: 10px;

    .el-form-item {
        margin-bottom: 2px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #33302d;

        :deep(.el-form-item__content) {
            display: flex;
            align-items: flex-start;
        }

        .el-form-item__content {
            .el-input {
                margin-right: 20px;
            }

            .edit_button {
                width: 220px;
            }
        }
    }

    .copy {
        margin-left: 5px;
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        font-weight: 300;
        color: #ff6b00;
        margin-right: 20px;
        cursor: pointer;
    }

    .extra {
        margin-left: 10px;
        color: #969696;
    }

    > h4 {
        padding-left: 14px;
        margin: 20px 0;
        font-size: 14px;
        color: rgb(0 0 0 / 65%);
        font-family: PingFangSC-Regular, 'PingFang SC';
        border-left: 4px solid #ff6b00;
    }
}

.el-empty {
    flex: 1;
}

.account_content {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
}

// .trillDialog {
:deep(.el-dialog__body) {
    padding-top: 14px;
    padding-bottom: 0;
}

// }
.trillForm {
    .el-form-item {
        margin-bottom: 18px;
    }

    .title {
        font-weight: 400;
        color: #33302d;
        font-size: 14px;
        margin-left: 44px;
    }

    .sync_btn {
        display: flex;
        align-items: center;

        .btn_text {
            font-size: 14px;
            font-weight: 300;
            color: #969696;
            margin-left: 9px;
        }
    }
}
</style>
